package cn.janescott.inner.space.webapp.controller;

import cn.janescott.inner.space.lib.constant.CommonEnums;
import cn.janescott.inner.space.lib.dto.Result;
import cn.janescott.inner.space.shiro.filter.CustomFormAuthenticationFilter;
import cn.janescott.inner.space.webapp.aop.WebAccessLogAnnotation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author scott
 * @date 2018/7/27
 */
@Controller
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String toLogin() {
        return "Login";
    }

    @WebAccessLogAnnotation(message = "登录", targetClass = LoginController.class)
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result submit(HttpServletRequest request) {
        Result result = null;
        String errorClass = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        logger.info(errorClass);
        String errorMessage = (String) request.getAttribute(CustomFormAuthenticationFilter.DEFAULT_ERROR_VALUE_ATTRIBUTE_NAME);
        logger.info(errorMessage);
        if (StringUtils.isEmpty(errorClass)) {
            result = Result.newInstance().setCode(CommonEnums.RESULT_CODE.C_200.getCode());
        } else if (UnknownAccountException.class.getName().equals(errorClass) ||
                IncorrectCredentialsException.class.getName().equals(errorClass)) {
            result = Result.newInstance().setCode(CommonEnums.RESULT_CODE.C_500.getCode()).setMessage("用户名或密码错误！");
        } else if (AuthenticationException.class.getName().equals(errorClass)) {
            result = Result.newInstance().setCode(CommonEnums.RESULT_CODE.C_500.getCode()).setMessage(errorClass);
        }
        return result;
    }

}
